package com.turing.draw.controller;

import com.alibaba.fastjson.JSONObject;
import com.turing.common.response.ResponseCode;
import com.turing.common.response.ResponseMessage;
import com.turing.common.response.ResponseVO;
import com.turing.common.spring.SpringApplicationContext;
import com.turing.common.util.FileUtils;
import com.turing.common.util.ResponseUtil;
import com.turing.common.util.Tools;
import com.turing.draw.model.domain.FileImage;
import com.turing.draw.service.FileImageService;
import com.turing.draw.service.PDFService;
import com.turing.draw.vo.out.ImageVO;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.io.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping("pdf")
public class PDFController {

    @Value("${fdfs.domain}")
    private String MEDIA_PATH;

    @Autowired
    private FileImageService fileImageService;

    @Autowired
    private PDFService pdfService;

    private static Log log = LogFactory.getLog(PDFController.class);

    @GetMapping("picOnePage")
    public ResponseVO<Object> picOnePage(@RequestParam("taskSn") String taskSn, @RequestParam("page") Integer page){
        byte[] bytes;
        try {
            FileImage fileImage = fileImageService.getFileImageByPage(taskSn, page);
            String path = MEDIA_PATH + fileImage.getImageUrl();
            File file = FileUtils.downloadFile(path);

            assert file != null;
            long start = System.nanoTime();
            long end = System.nanoTime();
//            log.info(">>>>>>>>>>>>compress pic micro time " + (end - start) / 1000 / 1000 + " ms");
            InputStream in = new FileInputStream(file);
            bytes = IOUtils.toByteArray(in);
            in.close();
            boolean delete = file.delete();
//            log.info("删除图片: " + delete);
            ImageVO imageVO = ImageVO.builder().base64(Base64.getEncoder().encodeToString(bytes))
                    .height(fileImage.getHeight())
                    .width(fileImage.getWidth()).build();
            return ResponseUtil.success(imageVO);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseUtil.error();
    }

    @PostMapping("picPageBatch")
    public ResponseVO<Object> picPageBatch(@RequestParam("taskSn") String taskSn, @RequestBody List<Integer> pages){
        byte[] bytes;
        try {
            List<FileImage> fileImages = fileImageService.getFileImageByPages(taskSn, pages);

            if(Tools.isEmpty(fileImages)){
                return ResponseUtil.error();
            }
            Map<Integer,ImageVO> result = new HashMap<>();
            for (FileImage fileImage : fileImages) {
                String path = MEDIA_PATH + fileImage.getImageUrl();
                File file = FileUtils.downloadFile(path);

                assert file != null;
                InputStream in = new FileInputStream(file);
                bytes = IOUtils.toByteArray(in);
                in.close();
                boolean delete = file.delete();
                log.info("删除图片: " + delete);
                ImageVO imageVO = ImageVO.builder().base64(Base64.getEncoder().encodeToString(bytes))
                        .height(fileImage.getHeight())
                        .width(fileImage.getWidth()).build();
                result.put(fileImage.getPageNo(),imageVO);
            }

            return ResponseUtil.success(result);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseUtil.error();

    }

    @GetMapping("downloadFile")
    public void downloadFile(@RequestParam("path") String path,HttpServletResponse response) throws IOException{

        if (path.contains("https")) {
            String replace = SpringApplicationContext.getProperty("fdfs.replace");
            String domain = SpringApplicationContext.getProperty("fdfs.domain");
            path = path.replaceAll(replace,domain);
        }
        File file = FileUtils.downloadFile(path);
        assert file != null;
        byte[] bytes = org.apache.commons.io.FileUtils.readFileToByteArray(file);
        response.getOutputStream().write(bytes);
    }

    @GetMapping("scoreOCRQuality")
    public void scoreOCRQuality(@RequestParam("taskSn") String taskSn,HttpServletResponse response) throws IOException{
        Map<String,List<Map<String,String>>> pages = pdfService.scoreOCRQuality(taskSn);
        XSSFWorkbook workbook = new XSSFWorkbook();
        if (pages != null) {

            for (String taskName : pages.keySet()) {
                XSSFSheet sheet = workbook.createSheet(taskName);
                List<Map<String,String>> pageInfos = pages.get(taskName);
                XSSFRow title = sheet.createRow(0);
                title.createCell(0).setCellValue("页码");
                title.createCell(1).setCellValue("倾斜角度");
                title.createCell(2).setCellValue("图片模糊度");
                title.createCell(3).setCellValue("文字置信度");
                //                title.createCell( 4 ).setCellValue( "OCR质量打分" );

                int row = 0;
                for (Map<String,String> pageInfo : pageInfos) {
                    row++;
                    XSSFRow rowV = sheet.createRow(row);
                    /*
                    * String tiltAngle = imageQualityMeasure.getString( "tiltAngle" );
                        String imageFuzzy = imageQualityMeasure.getString( "imageFuzzy" );
                        String textRecConfidence = imageQualityMeasure.getString( "textRecConfidence" );
                    * */

                    rowV.createCell(0).setCellValue(pageInfo.get("pageNo"));
                    rowV.createCell(1).setCellValue(pageInfo.get("tiltAngle"));
                    rowV.createCell(2).setCellValue(pageInfo.get("imageFuzzy"));
                    rowV.createCell(3).setCellValue(pageInfo.get("textRecConfidence"));
                    //                    rowV.createCell( 4 ).setCellValue( "暂无" );

                }
            }
        }
        ServletOutputStream outputStream = response.getOutputStream();
        response.setHeader("Cache-Control","no-cache, no-store, must-revalidate");
        response.setHeader("Pragma","no-cache");
        response.setHeader("Expires","0");
        response.setHeader("charset","utf-8");
        response.setHeader("Content-Disposition","attachment;filename=\"" + URLEncoder.encode("OCR识别准确率" + new Date().getTime() / 1000 + ".xlsx","UTF-8") + "\"");
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");

        //        workbook.write( fileOutputStream );
        workbook.write(outputStream);
    }

}
